package org.jparrow.framework.helper;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.jparrow.framework.annotation.Action;
import org.jparrow.framework.bean.Handler;
import org.jparrow.framework.bean.Request;
import org.jparrow.framework.util.ArrayUtil;
import org.jparrow.framework.util.CollectionUtil;

/**
 * 
 * 控制器助手类
 * 
 * @author supda
 * @date 2017-3-26
 *
 */
public final class ControllerHelper {

	/**
	 * 用于存放请求与控制器的映射关系（简称Action Map）
	 */
	private static final Map<Request, Handler> ACTION_MAP = 
			new HashMap<Request, Handler>();
	
	static {
		//获取所有Controller类
		Set<Class<?>> controllerClassSet = ClassHelper.getControllerClassSet();
		if(CollectionUtil.isNotEmpty(controllerClassSet)) {
			//遍历这些Controller类
			for(Class<?> controllerClass : controllerClassSet) {
				//获取Controller类中定义的方法
				Method[] methods = controllerClass.getDeclaredMethods();
				if(ArrayUtil.isNotEmpty(methods)) {
					//遍历这些Controller类中的方法
					for(Method method : methods) {
						//判断当前方法是否带有Action注解
						if(method.isAnnotationPresent(Action.class)) {
							//从Action注解中获取URL映射规则
							Action action = method.getAnnotation(Action.class);
							String mapping = action.value();
							//验证URL映射规则
							if(mapping.matches("\\w+:/\\w*")) {
								String[] array = mapping.split(":");
								if(ArrayUtil.isNotEmpty(array) && array.length == 2){
									//获取请求方法与请求路径
									String requestMethod = array[0];
									String requestPath = array[1];
									Request request = new Request(requestMethod, requestPath);
									Handler handler = new Handler(controllerClass, method);
									
									System.out.println("请求与控制器的映射关系,method:"+requestMethod+",path:"+requestPath+",handler:"+controllerClass.getName());
									
									//初始化ActionMap
									ACTION_MAP.put(request, handler);
								}
							}
						}
					}
				}
 			}
		}
		System.out.println("ACTION_MAP:"+ACTION_MAP);
	}
	
	//获取Handler
	public static Handler getHandler(String requestMethod, String requestPath) {
		Request request = new Request(requestMethod, requestPath);
		return ACTION_MAP.get(request);
	}
	
}
